<?php
define('ROOT_PATH',  str_replace('\\', '/', dirname(dirname(dirname(__FILE__))))."/");
require_once ROOT_PATH . 'lib/WeixinUtil.php';
require_once ROOT_PATH . "application/constant/Constant.php";

define("TOKEN", "liuliangegou");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();

class wechatCallbackapiTest {

	public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg() {
        date_default_timezone_set('PRC');  //设置默认时区
        require_once(ROOT_PATH . "config/config.inc.php"); //常用配置
        require_once(ROOT_PATH . "lib/lib_base.php");
        require_once(ROOT_PATH . "lib/lib_safe.php");
        require_once(ROOT_PATH . "lib/cls_db.php");
        
        $db = new Db_class(MYSQL_HOST, MYSQL_USER, MYSQL_PWD, MYSQL_DB, MYSQL_CHARSET);
        
    	$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $this->domain = $_SERVER['HTTP_HOST'];

		//extract post data
        if (!empty($postStr)) {

            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $time = time();
            $msgType = $postObj->MsgType;
            $Location_X = $postObj->Location_X;
            $Location_Y = $postObj->Location_Y;
            $Scale = $postObj->Scale;
            $Label = $postObj->Label;
            $PicUrl = $postObj->PicUrl;
            $MsgType = $postObj->MsgType;
            $MsgId = $postObj->MsgId;
            $Url = $postObj->Url;
            $Event = $postObj->Event;
            $Latitude = $postObj->Latitude;
            $Longitude = $postObj->Longitude;
            $Precision = $postObj->Precision;
            $EventKey = $postObj->EventKey;
            $Message = trim($postObj->Content);
            $token = TOKEN;

            $this->textTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Content><![CDATA[%s]]></Content>
						<FuncFlag>0<FuncFlag>	</xml>";
            $keyword = trim($postObj->Content);
            
            if ($msgType == "text") {
            	$this->insertHuifu($db, $fromUsername, $toUsername, $MsgId, $msgType, $keyword);
            	$this->doKeywordProcess($db, $keyword, $fromUsername, $toUsername, $msgType);
            } elseif ($msgType == "location") {
            	
            } elseif ($msgType == "image") {
            	if(!$db->getOne("select msgid from " . table('huifu') . " where msgid = $MsgId")) {
            		$this->insertHuifu($db, $fromUsername, $toUsername, $MsgId, $msgType, $keyword);
            		$imageurl = $postObj->PicUrl;
            		$filename = "upfile/wxpic/".$fromUsername.date("YmdHis").".jpg";
            		 
            		$this->get_file($imageurl,$filename);
            		 
            		$db->query("INSERT INTO " . table('huifupic') . " SET weixinid ='$fromUsername',picurl='$filename',wximageurl='$imageurl' ");
            		 
            		//回复信息
            		$contentStr = "图片上传成功!";
            		$resultStr = sprintf($this->textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
            		echo $resultStr;
            	}
            	exit();
            
            //菜单操作
            } elseif ($msgType == "event") {
            	$contentevent = $Event;
            	
				if($Event == 'CLICK' || $Event == 'VIEW') {
            		$this->insertHuifu($db, $fromUsername, $toUsername, $MsgId, $msgType, "CLICK$EventKey");
            	} else {
            		$this->insertHuifu($db, $fromUsername, $toUsername, $MsgId, $msgType, "$contentevent");
            	}
            	
            	if ($Event == 'subscribe') {
            		//更新微信会员表
            		$user = $db->getRow("select * from " . table("user") . " where openid = '$fromUsername'");
            		if($user) {
            			$user["follow_flag"] = "1";
            			$user["follow_time"] = date("Y-m-d H:i:s");
            			$user["update_time"] = date("Y-m-d H:i:s");
            			$db->update("user", $user, " and openid = '$fromUsername'");
            		} else {
            			$user["openid"] = $fromUsername;
            			$user["follow_flag"] = "1";
            			$user["follow_time"] = date("Y-m-d H:i:s");
            			$user["insert_time"] = date("Y-m-d H:i:s");
            			$user["update_time"] = date("Y-m-d H:i:s");
            			 
            			$db->insert("user", $user);
            		}

            		//回复信息
            		$setting = $db->getRow("SELECT * FROM " . table('setting'));
            		if($setting) {
            				$contentStr = WeixinUtil::urlAddWxid($setting["welcome_text"], $fromUsername);
			    			$contentStr = str_replace("\r\n", "\n", $contentStr);
            				$resultStr = sprintf($this->textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
            				echo $resultStr;
//             			if($setting["welcome_type"] == 1) {
//             				$contentStr = WeixinUtil::urlAddWxid($setting["welcome_text"], $fromUsername);
// 			    			$contentStr = str_replace("\r\n", "\n", $contentStr);
//             				$resultStr = sprintf($this->textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
//             				echo $resultStr;
//             			} else {
//             				$tuwens = array();
// 			    			$tuwen = array($setting['welcome_tuwen_title'],
// 			    							trim($setting['welcome_tuwen_desc']), 
// 			    							trim($setting['welcome_tuwen_pic']), 
// 			    							trim($setting['welcome_tuwen_url']));
// 			    			$tuwens[] = $tuwen;
//             				$tuwenStr = WeixinUtil::replyNews($tuwens, $fromUsername, $toUsername);
//     						echo $tuwenStr;
//             			}
            		} 
            		exit;
            	} else if ($Event == "unsubscribe") {
            		$user = $db->getRow("select * from " . table("user") . " where openid = '$fromUsername'");
            		$user["follow_time"] = date("Y-m-d H:i:s");
            		$user["update_time"] = date("Y-m-d H:i:s");
            		$db->update("user", $user, " and openid = '$fromUsername'");
            	} else if ($Event == 'CLICK') {
            		$keyword = $EventKey;
            		$this->doKeywordProcess($db, $keyword, $fromUsername, $toUsername, $msgType);
            	}
            } else if ($msgType == "voice") {
            	$contentStr = "哎呀，目前不能识别您发送的内容，请您用文字发送。";
            	$resultStr = sprintf($this->textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
            	
            	echo $resultStr;
            	exit;
            } else {
                $MsgId = $postObj->MsgId;
                $Url = $postObj->Url;
                $Event = $postObj->Event;
                $Latitude = $postObj->Latitude;
                $Longitude = $postObj->Longitude;
                $Precision = $postObj->Precision;
                $EventKey = $postObj->EventKey;
                $contentall = $MsgId . "#" . $Url . "#" . $Event . "#" . $Latitude . "#" . $Longitude . "#" . $Precision . "#" . $EventKey;
                $db->query("INSERT INTO " . table('huifu') . " SET fromuser='$fromUsername',touser='$toUsername',msgtype='$msgType',content='$contentall' ");
                $contentStr = "哎呀，目前不能识别您发送的内容，小编稍后会人工回复您！\n";
                $resultStr = sprintf($this->textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
                
                echo $resultStr;
                exit();
            }
        } else {
            $this->valid();
        }
    }
    
    function insertHuifu($db, $fromUser, $toUser, $msgId, $msgType, $keyword) {
    	
    	$db->query(" insert into " . table("huifu") 
    			 . " set fromuser = '$fromUser', "
    			 . " touser = '$toUser'," 
    			 . " msgid = '$msgId', " 
    			 . " msgtype = '$msgType', "
    			 . " content='$keyword'");
    }
    
    function doKeywordProcess($db, $keyword, $fromUsername, $toUsername, $msgType) {
    	$time = time();
    	$weixinkeyword = $db->getRow("SELECT * FROM " . table("weixin") . " where title like '%" . $keyword . "%' and isvalid=1 order by id desc");
    	if ($weixinkeyword) {
    		$contentStr = str_replace("\r\n", "\n", $weixinkeyword['content']);
    		$resultStr = sprintf($this->textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
    		echo $resultStr;
    		exit;
    	}
    	
    	$weixinkeyword = $db->getRow("SELECT * FROM " . table("weixin") . " where LOCATE(title,'" . $keyword . "')>0 and isvalid=1  order by id desc");
    	if ($weixinkeyword) {
    		$contentStr = str_replace("\r\n", "\n", $weixinkeyword['content']);
    		$resultStr = sprintf($this->textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
    		echo $resultStr;
    		exit;
    	}
    	
    	//图文关键字识别
    	$restuwen = $db->query("select * from " . table('tuwen') . " where keyword like '%" . $keyword . "%' and isvalid=1 order by sequence desc,id desc ");
    	while ($rstuwen = $db->fetch_array($restuwen)) {
    		$tuwen = array($rstuwen['title'], trim($rstuwen['content']), trim($rstuwen['picurl']), trim($rstuwen['linkurl']));
    		$tuwens[] = $tuwen;
    	}
    	if (count($tuwens) > 0) {
    		$tuwenStr = WeixinUtil::replyNews($tuwens, $fromUsername, $toUsername);
    		echo $tuwenStr;
    		exit;
    	}
    	
    	$setting = $db->getRow("SELECT * FROM " . table("setting"));
    	if($setting) {
    		$contentStr = $setting["default_text_return"];
    		$contentStr = str_replace("\r\n", "\n", $contentStr);
    	
    		echo sprintf($this->textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
    		exit();
    	}
	}
    	 
    function get_file($url,$pic_name){
    	set_time_limit(24*60*60*60); //限制最大的执行时间
    	$newfname=$pic_name;//文件PATH
    	$file=fopen($url,'rb');
    
    	if($file){
    		$newf=fopen($newfname,'wb');
    
    		if($newf){
    
    			while(!feof($file)){
    				fwrite($newf,fread($file,1024*8),1024*8);
    			}
    		}
    
    		if($file){
    			fclose($file);
    		}
    
    		if($newf){
    			fclose($newf);
    		}
    	}
    }
    
    
    public function sprintfdata($textTpl, $fromUsername, $toUsername, $time, $msgType,$responseMsg) {
    	$responseMsg = str_replace("&wxid", "&wxid=" + $toUsername, $responseMsg);
    	$responseMsg = str_replace("\r\n", "\n", $responseMsg);
    	$responseMsg = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $responseMsg);
    }

	private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}


?>
